﻿import { useState, useRef } from "react"
import { useEditorState } from "../utils/hooks"

export default function EditorTab() {
  const [isCapturingForEditor, setIsCapturingForEditor] = useState(false)
  const editorRef = useRef<HTMLDivElement>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)

  // 使用持久化状态管理编辑器内容
  const {
    content: editorContent,
    setContent: setEditorContent,
    isLoading: contentLoading
  } = useEditorState()

  // 确保 editorContent 不为 null 或 undefined
  const safeEditorContent = editorContent || ""

  // HTML 转 Markdown 转换函数
  const htmlToMarkdown = (html: string): string => {
    if (!html || typeof html !== 'string') return ""
    
    let markdown = html

    // 处理标题
    markdown = markdown.replace(/<h1[^>]*>(.*?)<\/h1>/gi, '# $1\n\n')
    markdown = markdown.replace(/<h2[^>]*>(.*?)<\/h2>/gi, '## $1\n\n')
    markdown = markdown.replace(/<h3[^>]*>(.*?)<\/h3>/gi, '### $1\n\n')
    markdown = markdown.replace(/<h4[^>]*>(.*?)<\/h4>/gi, '#### $1\n\n')
    markdown = markdown.replace(/<h5[^>]*>(.*?)<\/h5>/gi, '##### $1\n\n')
    markdown = markdown.replace(/<h6[^>]*>(.*?)<\/h6>/gi, '###### $1\n\n')

    // 处理粗体和斜体
    markdown = markdown.replace(/<strong[^>]*>(.*?)<\/strong>/gi, '**$1**')
    markdown = markdown.replace(/<b[^>]*>(.*?)<\/b>/gi, '**$1**')
    markdown = markdown.replace(/<em[^>]*>(.*?)<\/em>/gi, '*$1*')
    markdown = markdown.replace(/<i[^>]*>(.*?)<\/i>/gi, '*$1*')

    // 处理下划线和删除线
    markdown = markdown.replace(/<u[^>]*>(.*?)<\/u>/gi, '<u>$1</u>')
    markdown = markdown.replace(/<s[^>]*>(.*?)<\/s>/gi, '~~$1~~')
    markdown = markdown.replace(/<strike[^>]*>(.*?)<\/strike>/gi, '~~$1~~')
    markdown = markdown.replace(/<del[^>]*>(.*?)<\/del>/gi, '~~$1~~')

    // 处理链接
    markdown = markdown.replace(/<a[^>]*href=["']([^"']*)["'][^>]*>(.*?)<\/a>/gi, '[$2]($1)')

    // 处理图片
    markdown = markdown.replace(/<img[^>]*src=["']([^"']*)["'][^>]*alt=["']([^"']*)["'][^>]*>/gi, '![$2]($1)')
    markdown = markdown.replace(/<img[^>]*alt=["']([^"']*)["'][^>]*src=["']([^"']*)["'][^>]*>/gi, '![$1]($2)')
    markdown = markdown.replace(/<img[^>]*src=["']([^"']*)["'][^>]*>/gi, '![]($1)')

    // 处理列表
    markdown = markdown.replace(/<ul[^>]*>(.*?)<\/ul>/gis, (match, content) => {
      const items = content.match(/<li[^>]*>(.*?)<\/li>/gis) || []
      return items.map((item: string) => {
        const text = item.replace(/<li[^>]*>(.*?)<\/li>/is, '$1')
        return `- ${htmlToMarkdown(text?.trim() || "")}`
      }).join('\n') + '\n\n'
    })

    markdown = markdown.replace(/<ol[^>]*>(.*?)<\/ol>/gis, (match, content) => {
      const items = content.match(/<li[^>]*>(.*?)<\/li>/gis) || []
      return items.map((item: string, index: number) => {
        const text = item.replace(/<li[^>]*>(.*?)<\/li>/is, '$1')
        return `${index + 1}. ${htmlToMarkdown(text?.trim() || "")}`
      }).join('\n') + '\n\n'
    })

    // 处理段落
    markdown = markdown.replace(/<p[^>]*>(.*?)<\/p>/gi, '$1\n\n')
    markdown = markdown.replace(/<div[^>]*>(.*?)<\/div>/gi, '$1\n\n')

    // 处理换行
    markdown = markdown.replace(/<br[^>]*>/gi, '\n')
    markdown = markdown.replace(/<\/br>/gi, '\n')

    // 处理代码
    markdown = markdown.replace(/<code[^>]*>(.*?)<\/code>/gi, '`$1`')
    markdown = markdown.replace(/<pre[^>]*>(.*?)<\/pre>/gis, '```\n$1\n```\n\n')

    // 处理引用
    markdown = markdown.replace(/<blockquote[^>]*>(.*?)<\/blockquote>/gis, (match, content) => {
      const lines = content.split('\n').filter((line: string) => line?.trim())
      return lines.map((line: string) => `> ${htmlToMarkdown(line?.trim() || "")}`).join('\n') + '\n\n'
    })

    // 清理多余的标签和空白
    markdown = markdown.replace(/<[^>]*>/g, '')
    markdown = markdown.replace(/\n{3,}/g, '\n\n')
    markdown = markdown.replace(/^\s+|\s+$/g, '')

    return markdown
  }

  // 富文本编辑器功能
  const execCommand = (command: string, value?: string) => {
    document.execCommand(command, false, value)
    editorRef.current?.focus()
  }

  // 插入图片到编辑器的通用函数
  const insertImageToEditor = (imageSrc: string, altText: string = '图片') => {
    if (!editorRef.current) return

    // 确保编辑器获得焦点
    editorRef.current.focus()

    // 创建图片元素
    const img = document.createElement('img')
    img.src = imageSrc
    img.alt = altText
    img.style.maxWidth = '100%'
    img.style.height = 'auto'
    img.style.display = 'block'
    img.style.margin = '8px 0'
    img.style.borderRadius = '4px'
    img.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)'

    // 获取当前光标位置
    const selection = window.getSelection()
    if (selection && selection.rangeCount > 0) {
      const range = selection.getRangeAt(0)
      range.deleteContents()
      range.insertNode(img)
      
      // 将光标移到图片后面
      range.setStartAfter(img)
      range.setEndAfter(img)
      selection.removeAllRanges()
      selection.addRange(range)
    } else {
      // 如果没有选择，直接添加到编辑器末尾
      editorRef.current.appendChild(img)
      
      // 添加换行
      const br = document.createElement('br')
      editorRef.current.appendChild(br)
    }

    // 更新编辑器内容状态
    setEditorContent(editorRef.current.innerHTML)
  }

  // 插入网络图片
  const insertImageFromUrl = () => {
    const url = prompt('请输入图片URL:')
    if (url) {
      insertImageToEditor(url, '网络图片')
    }
  }

  // 插入本地图片
  const insertImageFromFile = () => {
    fileInputRef.current?.click()
  }

  // 处理文件选择
  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (!file) return

    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件！')
      return
    }

    // 检查文件大小 (限制为 5MB)
    if (file.size > 5 * 1024 * 1024) {
      alert('图片文件大小不能超过 5MB！')
      return
    }

    const reader = new FileReader()
    reader.onload = (e) => {
      const result = e.target?.result as string
      if (result) {
        insertImageToEditor(result, file.name)
      }
    }
    reader.readAsDataURL(file)

    // 清空文件输入
    event.target.value = ''
  }

  // 浏览器截屏功能（用于编辑器）
  const captureScreenForEditor = async () => {
    try {
      setIsCapturingForEditor(true)

      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })
      
      if (!tab.id) {
        throw new Error("无法获取当前标签页")
      }

      const dataUrl = await chrome.tabs.captureVisibleTab(tab.windowId, {
        format: "png",
        quality: 100
      })

      insertImageToEditor(dataUrl, '浏览器截屏')
    } catch (err) {
      alert(err instanceof Error ? err.message : "截屏失败")
    } finally {
      setIsCapturingForEditor(false)
    }
  }

  const insertLink = () => {
    const url = prompt('请输入链接地址:')
    if (url) {
      execCommand('createLink', url)
    }
  }

  const clearFormatting = () => {
    execCommand('removeFormat')
  }

  const exportAsHTML = () => {
    if (!safeEditorContent) return
    
    const blob = new Blob([safeEditorContent], { type: 'text/html' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.download = `document-${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.html`
    link.href = url
    link.click()
    URL.revokeObjectURL(url)
  }

  const exportAsMarkdown = () => {
    if (!safeEditorContent) return
    
    const markdown = htmlToMarkdown(safeEditorContent)
    const blob = new Blob([markdown], { type: 'text/markdown' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.download = `document-${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.md`
    link.href = url
    link.click()
    URL.revokeObjectURL(url)
  }

  // 清空编辑器
  const clearEditor = () => {
    setEditorContent('')
    if (editorRef.current) {
      editorRef.current.innerHTML = ''
    }
  }

  // 工具栏按钮样式
  const toolbarButtonStyle = {
    padding: '4px 8px',
    backgroundColor: 'white',
    border: '1px solid #ddd',
    borderRadius: '3px',
    cursor: 'pointer',
    fontSize: '12px',
    minWidth: '24px',
    height: '24px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center'
  }

  return (
    <div>
      <h3 style={{ marginTop: 0, color: "#333" }}>
         富文本编辑器
      </h3>

      {/* 隐藏的文件输入 */}
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={handleFileSelect}
        style={{ display: 'none' }}
      />

      {/* 工具栏 */}
      <div style={{ 
        display: 'flex', 
        flexWrap: 'wrap', 
        gap: '4px', 
        marginBottom: 12,
        padding: '8px',
        backgroundColor: '#f8f9fa',
        borderRadius: '4px',
        border: '1px solid #ddd'
      }}>
        <button
          onClick={() => execCommand('bold')}
          style={toolbarButtonStyle}
          title="粗体">
          <strong>B</strong>
        </button>
        <button
          onClick={() => execCommand('italic')}
          style={toolbarButtonStyle}
          title="斜体">
          <em>I</em>
        </button>
        <button
          onClick={() => execCommand('underline')}
          style={toolbarButtonStyle}
          title="下划线">
          <u>U</u>
        </button>
        <button
          onClick={() => execCommand('strikeThrough')}
          style={toolbarButtonStyle}
          title="删除线">
          <s>S</s>
        </button>
        
        <div style={{ width: '1px', backgroundColor: '#ddd', margin: '0 4px' }}></div>
        
        <button
          onClick={() => execCommand('justifyLeft')}
          style={toolbarButtonStyle}
          title="左对齐">
          
        </button>
        <button
          onClick={() => execCommand('justifyCenter')}
          style={toolbarButtonStyle}
          title="居中">
          
        </button>
        <button
          onClick={() => execCommand('justifyRight')}
          style={toolbarButtonStyle}
          title="右对齐">
          
        </button>
        
        <div style={{ width: '1px', backgroundColor: '#ddd', margin: '0 4px' }}></div>
        
        <button
          onClick={() => execCommand('insertUnorderedList')}
          style={toolbarButtonStyle}
          title="无序列表">
          
        </button>
        <button
          onClick={() => execCommand('insertOrderedList')}
          style={toolbarButtonStyle}
          title="有序列表">
          
        </button>
        
        <div style={{ width: '1px', backgroundColor: '#ddd', margin: '0 4px' }}></div>
        
        <button
          onClick={insertLink}
          style={toolbarButtonStyle}
          title="插入链接">
          
        </button>
        
        {/* 图片插入按钮组 */}
        <div style={{ display: 'flex', gap: '2px' }}>
          <button
            onClick={insertImageFromUrl}
            style={toolbarButtonStyle}
            title="插入网络图片">
            
          </button>
          <button
            onClick={insertImageFromFile}
            style={toolbarButtonStyle}
            title="插入本地图片">
            
          </button>
          <button
            onClick={captureScreenForEditor}
            disabled={isCapturingForEditor}
            style={{
              ...toolbarButtonStyle,
              backgroundColor: isCapturingForEditor ? '#ccc' : 'white',
              cursor: isCapturingForEditor ? 'not-allowed' : 'pointer'
            }}
            title="截屏插入">
            
          </button>
        </div>
        
        <div style={{ width: '1px', backgroundColor: '#ddd', margin: '0 4px' }}></div>
        
        <button
          onClick={clearFormatting}
          style={toolbarButtonStyle}
          title="清除格式">
          
        </button>
      </div>

      {/* 编辑器区域 */}
      <div
        ref={editorRef}
        contentEditable
        onInput={(e) => setEditorContent(e.currentTarget.innerHTML)}
        style={{
          minHeight: '200px',
          padding: '12px',
          border: '1px solid #ddd',
          borderRadius: '4px',
          backgroundColor: 'white',
          fontSize: '14px',
          lineHeight: '1.5',
          outline: 'none',
          overflowY: 'auto'
        }}
        dangerouslySetInnerHTML={{ __html: safeEditorContent }}
      />

      {/* 加载状态指示器 */}
      {contentLoading && (
        <div style={{
          textAlign: 'center',
          padding: '8px',
          color: '#666',
          fontSize: '12px',
          backgroundColor: '#f8f9fa',
          borderRadius: '4px',
          marginTop: '8px'
        }}>
           正在加载编辑器内容...
        </div>
      )}

      {/* 编辑器操作按钮 */}
      <div style={{ display: 'flex', gap: '8px', marginTop: 12 }}>
        <button
          onClick={exportAsMarkdown}
          disabled={!safeEditorContent.trim()}
          style={{
            flex: 1,
            padding: '8px',
            backgroundColor: safeEditorContent.trim() ? '#6f42c1' : '#ccc',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            fontSize: '12px',
            cursor: safeEditorContent.trim() ? 'pointer' : 'not-allowed'
          }}>
           导出MD
        </button>
        
        <button
          onClick={exportAsHTML}
          disabled={!safeEditorContent.trim()}
          style={{
            flex: 1,
            padding: '8px',
            backgroundColor: safeEditorContent.trim() ? '#28a745' : '#ccc',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            fontSize: '12px',
            cursor: safeEditorContent.trim() ? 'pointer' : 'not-allowed'
          }}>
           导出HTML
        </button>
        
        <button
          onClick={clearEditor}
          style={{
            flex: 1,
            padding: '8px',
            backgroundColor: '#dc3545',
            color: 'white',
            border: 'none',
            borderRadius: '4px',
            fontSize: '12px',
            cursor: 'pointer'
          }}>
           清空
        </button>
      </div>

      <div style={{ marginTop: 12, fontSize: '11px', color: '#666' }}>
         提示：支持富文本格式，可插入网络图片、本地图片和浏览器截屏，内容会自动保存
      </div>
    </div>
  )
}
